package com.apobates.forum.orize.servlet;

import com.apobates.forum.orize.core.OrizeAuthCommonHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * Orize验证失败时的
 * @author xiaofanku@live.cn
 * @since 20210822
 */
@WebServlet("/orize/result")
public class OrizeResultServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Object orizeLog = request.getSession().getAttribute("__orizeLog");
        Map<String,String> orizeLogMap = new HashMap<>();
        if(orizeLog instanceof Map){
            orizeLogMap = (Map)orizeLog;
        }
        //始终从请求中查询
        boolean isAjax = OrizeAuthCommonHelper.isAjaxRequest(request); //BUG:"true".equalsIgnoreCase(orizeLogMap.get("reqAjax"));
        response.setContentType(isAjax?"application/json;charset=utf-8":"text/html;charset=UTF-8");
        response.setHeader("cache-control", "no-cache");
        request.getSession().removeAttribute("__orizeLog");
        //
        PrintWriter out = response.getWriter();
        out.println(isAjax?writeJsonResponse(orizeLogMap):writeHTMLPage(orizeLogMap));
        out.flush();
    }

    private String writeHTMLPage(Map<String,String> data){
        StringBuffer sb = new StringBuffer();
        String html = "<!DOCTYPE html>" +
                "<html>" +
                "    <head>" +
                "        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">" +
                "        <title>出错了</title>" +
                "    </head>" +
                "    <body class=\"orize_result_log\">";
        sb.append(html);
        //
        sb.append("<div id=\"subject\"><p>");
        sb.append(Optional.ofNullable(data.get("message")).orElse("Orize资源验证失败"));
        sb.append("</p></div><div id=\"detail\"><ul>");
        //
        Map<String,String> chnNamesMap = namesMap();
        for(Map.Entry<String,String> entry:data.entrySet()){
            sb.append("<li><dl><dt>"+chnNamesMap.get(entry.getKey()));
            sb.append("</dt><dd>"+entry.getValue());
            sb.append("</dd></dl></li>");
        }
        //
        sb.append("</ul></div></body></html>");
        return sb.toString();
    }

    private String writeJsonResponse(Map<String,String> data){
        Map<String,String> result = new HashMap<>(data);
        result.put("message", "Orize资源验证失败");
        result.put("level", "err");
        result.put("input", "orize.log");
        return new Gson().toJson(result, new TypeToken<Map<String,String>>(){}.getType());
    }

    private Map<String,String> namesMap(){
        Map<String,String> map = new HashMap<>();
        map.put("reqMethod", "请求方法");
        map.put("reqPath", "请求路径");
        map.put("reqAjax", "Ajax请求");
        //
        map.put("resPath", "资源中定义的路径");
        map.put("resMethod", "资源中允许的方法");
        map.put("resAction", "资源中定义的动作");
        map.put("resSpot", "资源中定义的动作请求标识");
        return map;
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
    }
}
